/* 
 * shamefully copy from AnFetion.
 * more see: http://code.google.com/p/anfetion/
 */
package person.bangbang.im.Androidgin.Fetion;

import java.util.ArrayList;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.net.Uri;
import android.provider.Contacts;

public final class MiscUtil {
    public static final int DIS_CONNECT_NOTIFY_ID = 0x782a;

    public static final ColorFilter COLORFILTER_GRAWSCALE;
    public static final ColorFilter COLORFILTER_NORMAL;
    static {
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        COLORFILTER_GRAWSCALE = new ColorMatrixColorFilter(cm);
        cm.setSaturation(1);
        COLORFILTER_NORMAL = new ColorMatrixColorFilter(cm);
    }

    private static Context appContext = null;
    private static NotificationManager nManger = null;

//    public static AlertDialog getInviteDialog(final FetionListFriends ctx) {
//        final View view = LayoutInflater.from(ctx).inflate(R.layout.invite, null);
//        FetionFriend f = ctx.mBoundService.getMyself();
//        final EditText edit_nick = (EditText) view.findViewById(R.id.nickname);
//        view.findViewById(R.id.import_contacts).setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View view) {
//                Intent i = new Intent(Intent.ACTION_PICK);
//                i.setData(Uri.parse("content://contacts/phones"));
//                ctx.startActivityForResult(i, FetionListFriends.IMPORT_PHONE_REQUEST_ID);
//            }
//
//        });
//        edit_nick.setText(f.getNickName());
//        AlertDialog dialog = new AlertDialog.Builder(ctx).setTitle("添加好友").setView(view).setPositiveButton(
//                "确定", new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        if (!MiscUtil.checkIsOnline()) return;
//
//                        Thread t = new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                String mobile = ((EditText) view.findViewById(R.id.mobileNo)).getText()
//                                        .toString();
//                                String nick = edit_nick.getText().toString();
//                                String uri = "tel:" + mobile;
//                                int ret = ctx.mBoundService.sendInvite(uri, nick);
//                                if (ret == 0) {
//                                    MiscUtil.notifyInviteFail(ctx);
//                                } else if (ret == 2) {
//                                    ArrayList<FetionFriend> buddies = getBuddies();
//                                    FetionFriend ff = getFriend(uri, buddies);
//                                    if (ff == null) {
//                                        ff = new FetionFriend();
//                                        ff.mobile_no = mobile;
//                                        ff.Uri = "tel:" + mobile;
//                                        ff.type = Settings.TYPE_NOT_FRIEND;
//                                        ff.isMe = false;
//                                        buddies.add(ff);
//                                        MiscUtil.notifyFriendChange(ctx);
//                                    }
//                                }
//
//                            }
//                        });
//                        t.start();
//                    }
//
//                }).setNegativeButton("取消", null).create();
//        return dialog;
//    }

//    public static ArrayList<FetionFriend> getBuddies() {
//        FetionService service = FetionService.getService();
//        if (service == null || !FetionService.isLogined()) {
//            return null;
//        }
//        return service.getReserveNotify().getBuddies();
//    }

//    public static AlertDialog getSetStautsMenu(final FetionListFriends ctx, final FetionFriend friend) {
//        int sel = 0, size = Settings.STATUS_MENU_IDS.length;
//        for (; sel < size; sel++) {
//            if (friend.getOnlineStatusInt() == Settings.STATUS_MENU_IDS[sel]) {
//                break;
//            }
//        }
//        return new AlertDialog.Builder(ctx).setTitle("更改在线状态").setSingleChoiceItems(Settings.STATUS_MENU,
//                sel, new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        if (!MiscUtil.checkIsOnline()) return;
//
//                        final int newstatus = Settings.STATUS_MENU_IDS[which];
//                        if (friend.getOnlineStatusInt() != newstatus) {
//                            ctx.runOnUiThread(new Runnable() {
//
//                                @Override
//                                public void run() {
//                                    if (ctx.mBoundService.setPresence(newstatus)) {
//                                        friend.setOnlineStatus(newstatus);
//                                        ctx.refreshSelf();
//                                        // MiscUtil.notifyReceival(ctx);
//                                    }
//                                }
//
//                            });
//                        }
//                        dialog.dismiss();
//                    }
//
//                }).create();
//    }

    public static void notifyReceival(Context ctx) {
        Intent in = new Intent(Settings.ACTION_RECEIVE_MESSAGE);
        getContext(ctx).sendBroadcast(in);
    }

    public static void notifyInviteFail(Context ctx) {
        Intent in = new Intent(Settings.ACTION_SENT_INVITE_FAIL);
        getContext(ctx).sendBroadcast(in);
    }

//    public static AlertDialog getReconnectDialog(final FetionListFriends ctx) {
//        AlertDialog dialog = new AlertDialog.Builder(ctx).create();
//        dialog.setTitle("系统提示");
//        dialog.setMessage("与服务器断开连接！");
//        dialog.setButton("返回登陆框", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                ctx.isClosing = true;
//                ctx.mBoundService.close();
//                Intent intent = new Intent(ctx.getApplicationContext(), FetionLoginActivity.class);
//                ctx.startActivity(intent);
//                ctx.finish();
//            }
//        });
//        dialog.setButton2("退出程序", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                ctx.isClosing = true;
//                ctx.mBoundService.close();
//                // releaseAll();
//                getContext(ctx).stopService(MiscUtil.getFetionServiceIntent(ctx));
//                ctx.finish();
//            }
//        });
//        return dialog;
//    }

//    public static Intent getFetionServiceIntent(Context ctx) {
//        return new Intent(getContext(ctx), FetionService.class);
//    }

    public static void notifyFriendChange(Context ctx) {
        Intent in = new Intent(Settings.ACTION_FRIEND_CHANGE);
        getContext(ctx).sendBroadcast(in);
    }

//    public static Intent getHome(Context ctx) {
//        Intent intent = new Intent(getContext(ctx), FetionListFriends.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
//        return intent;
//    }

//    public static void notifyDisconnect(Context ctx, String message, boolean failed) {
//        Notification info = new Notification(R.drawable.fetion, message, System.currentTimeMillis());
//        if (failed) {
//            info.defaults = Notification.DEFAULT_SOUND;
//            Intent i = new Intent(getContext(ctx), AnFetion.class);
//            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            i.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//            PendingIntent appIntent = PendingIntent.getActivity(getContext(ctx), 0, i,
//                    PendingIntent.FLAG_CANCEL_CURRENT);
//            info.setLatestEventInfo(getContext(ctx), message, "", appIntent);
//        } else {
//            Intent i = new Intent(Settings.ACTION_RECONNECT_CLEAR);
//            PendingIntent appIntent = PendingIntent
//                    .getBroadcast(ctx, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
//            info.setLatestEventInfo(getContext(ctx), message, "", appIntent);
//        }
//
//        ((NotificationManager) getContext(ctx).getSystemService(Context.NOTIFICATION_SERVICE)).notify(
//                DIS_CONNECT_NOTIFY_ID, info);
//    }
//
    public static Context getContext(Context ctx) {
        if (appContext == null) {
            appContext = ctx.getApplicationContext();
        }
        return appContext;
    }

//    public static boolean checkIsOnline() {
//        if (Settings.DEBUG) Log.d(Settings.TAG, "currentStatus is " + FetionService.isLogined());
//        if (FetionService.isLogined()) {
//            return true;
//        }
//        Toast.makeText(getContext(null), "飞信断线中, 禁止此操作!", Toast.LENGTH_SHORT).show();
//        return false;
//    }

    public static NotificationManager getNotificationManager(Context ctx) {
        if (nManger == null) {
            nManger = (NotificationManager) getContext(ctx).getSystemService(Context.NOTIFICATION_SERVICE);
        }
        return nManger;
    }

    public static void cancelNotification(Context ctx, int id) {
        if (id <= 0) return;
        getNotificationManager(ctx).cancel(id);
    }

    public static FetionFriend getFriend(String uri, ArrayList<FetionFriend> buddies) {
        if (uri == null || uri.equals("") || buddies == null || buddies.isEmpty()) {
            return null;
        }
        int size = buddies.size();
        for (int i = 0; i < size; i++) {
            FetionFriend ff = buddies.get(i);
            if (ff.Uri.equals(uri)) {
                return ff;
            }
        }
        return null;
    }

    public static FetionFriend getFriendByMobile(String mobile, ArrayList<FetionFriend> buddies) {
        if (mobile == null || mobile.equals("") || buddies == null || buddies.isEmpty()) {
            return null;
        }
        int size = buddies.size();
        for (int i = 0; i < size; i++) {
            FetionFriend ff = buddies.get(i);
            if (mobile.equals(ff.mobile_no)) {
                return ff;
            }
        }
        return null;
    }

    public static boolean removeFriend(String uri, ArrayList<FetionFriend> buddies) {
        int size = buddies.size();
        for (int j = 0; j < size; j++) {
            if (buddies.get(j).Uri.equals(uri)) {
                buddies.remove(j);
                return true;
            }
        }
        return false;
    }

//    public static int getFriendIcon(FetionFriend friend) {
//        int drawable = R.drawable.user_offline;
//        switch (friend.getOnlineStatusInt()) {
//            case Settings.STATUS_OFFLINE:
//                drawable = R.drawable.user_offline;
//                if (friend.IsMobileNo) {
//                    drawable = R.drawable.mobilebuddy;
//                }
//                break;
//            case Settings.STATUS_AWAY:
//                drawable = R.drawable.user_away;
//                break;
//            case Settings.STATUS_HIDDEN:
//                drawable = R.drawable.user_hidden;
//                break;
//            case Settings.STATUS_ONLINE:
//                drawable = R.drawable.user_online;
//                break;
//            case Settings.STATUS_BUSY:
//                drawable = R.drawable.user_busy;
//                break;
//        }
//        return drawable;
//    }

    public static String getMobile(Context ctx, Uri uri) {
        Cursor c = getContext(ctx).getContentResolver().query(uri, new String[] { Contacts.Phones.NUMBER },
                null, null, null);
        if (c != null && c.moveToNext()) {
            String mobile = c.getString(0);
            return mobile.replace("-", "");
        }
        return null;
    }

    public static String toMobile(String s) {
        if (s == null) return null;
        if (s.startsWith("+86")) {
            s = s.substring(3);
        }
        if (s.startsWith("1") && s.length() == 11) {
            return s;
        }
        return null;
    }
}
